package com.liliudong.template.biz.service.sys.impl;

import cn.hutool.core.collection.CollUtil;
import com.liliudong.template.biz.mapper.sys.SysDictItemMapper;
import com.liliudong.template.biz.service.sys.SysDictItemService;
import com.liliudong.template.common.constant.ExMessage;
import com.liliudong.template.common.entity.sys.SysDictItem;
import com.liliudong.template.common.exception.BizException;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.liliudong.template.common.entity.sys.table.SysDictItemTableDef.SYS_DICT_ITEM;

/**
 * 服务实现
 *
 * @author liudo
 * @date 2024-08-01 20:27:02
 */
@Service
@RequiredArgsConstructor
public class SysDictItemServiceImpl extends ServiceImpl<SysDictItemMapper, SysDictItem>
        implements SysDictItemService {

    @Override
    public void saveBathByDictId(Long dictId, List<SysDictItem> sysDictItems) {
        if (CollUtil.isEmpty(sysDictItems)) {
            return;
        }
        if (Objects.isNull(dictId)) {
            throw new BizException(ExMessage.DICT_EMPTY);
        }
        sysDictItems.forEach(sysDictItem -> sysDictItem.setDictId(dictId));
        this.saveBatch(sysDictItems);
    }

    @Override
    public long countByDictId(Long dictId) {
        return count(SYS_DICT_ITEM.DICT_ID.eq(dictId));
    }

    @Override
    public void removeByDictId(Long dictId) {
        removeById(SYS_DICT_ITEM.DICT_ID.eq(dictId));
    }

    @Override
    public List<SysDictItem> listByDictId(Long dictId) {
        return list(SYS_DICT_ITEM.DICT_ID.eq(dictId));
    }

    @Override
    public Map<Long, List<SysDictItem>> listMapsByDictIds(List<Long> dictIds) {
        return list(SYS_DICT_ITEM.DICT_ID.in(dictIds))
                .stream()
                .collect(Collectors.groupingBy(SysDictItem::getDictId));
    }
}
